﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using SmartMobile.Data;
using SmartMobile.Data;
using SMARTMobile.Common;
using SMARTMobile.Framework;
using SMARTMobile.Models;
using SMARTMobile.Models.Local;
using SMARTMobile.Models.Xml;
using SMARTMobile.Services.SMARTMobileServiceReference;
using SMARTMobile.WinPhone;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Xml.Linq;

namespace SMARTMobile.ViewModels
{
    public class RequestState
    {
        // This class stores the state of the request. 
        const int BUFFER_SIZE = 1024;
        public StringBuilder requestData;
        public byte[] bufferRead;
        public WebRequest request;
        public WebResponse response;
        public Stream responseStream;
        public RequestState()
        {
            bufferRead = new byte[BUFFER_SIZE];
            requestData = new StringBuilder("");
            request = null;
            responseStream = null;
        }
    }

    public partial class ThietDatViewModel : ViewModelBase
    {
        private string _webService;
        private string _phoneNumber;
        private string _passWord;
        private string _IdDevice;
        private bool _isSS;
        private bool _isSaleSP;
        private ObservableCollection<ARSALESP> _saleSPList;
        private ObservableCollection<DoiTuongModel> _doituongList;
        private ObservableCollection<Distributor> _distributorList;
        private ObservableCollection<ARSS> _arssList;
        private ARSALESP _selectedSaleSP;
        private DoiTuongModel _selectedDoiTuong;
        private ARSS _selectedSS;
        private Distributor _selectedDistributor;
        private ReloadDataSmartPhoneSoapClient _proxy;

        SmartMobileDBContext _smartMobileContext;

        public ThietDatViewModel()
        {
            this.CreateConnection();
            this.SaveCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteSaveCommand
            };

            this.ExitCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteExitCommand
            };

            this.UpdateCommand = new CommandRoute
            {
                ExecuteHandler = this.ExecuteUpdateCommand
            };

            object uniqueId;
            var hexString = string.Empty;
            string test = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
            byte[] byteData = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId");
            string imei = System.Convert.ToBase64String(byteData);
            this.IDDevice = string.IsNullOrEmpty(imei) ? string.Empty : imei;
            Webservice = "wsnokia.smartbs.vn";
        }

        #region Properties

        public bool IsSaleSP
        {
            get
            {
                return this._isSaleSP;
            }
            set
            {
                this._isSaleSP = value;
                RaisePropertyChanged("IsSaleSP");
            }
        }

        public bool IsSS
        {
            get
            {
                return this._isSS;
            }
            set
            {
                this._isSS = value;
                RaisePropertyChanged("IsSS");
            }
        }

        public string IDDevice
        {
            get
            {
                return this._IdDevice;
            }
            set
            {
                this._IdDevice = value;
                RaisePropertyChanged("IDDevice");
            }
        }

        public string Webservice
        {
            get
            {
                return this._webService;
            }
            set
            {
                this._webService = value;
                RaisePropertyChanged("Webservice");
            }
        }

        public string PhoneNumber
        {
            get
            {
                return this._phoneNumber;
            }
            set
            {
                this._phoneNumber = value;
                RaisePropertyChanged("PhoneNumber");
            }
        }

        public string PassWord
        {
            get
            {
                return this._passWord;
            }
            set
            {
                this._passWord = value;
                RaisePropertyChanged("PassWord");
            }
        }

        public ObservableCollection<Distributor> DistributorList
        {
            get
            {
                return this._distributorList;
            }
            set
            {
                this._distributorList = value;
                RaisePropertyChanged("DistributorList");
            }
        }

        public ObservableCollection<ARSS> ArssList
        {
            get
            {
                return this._arssList;
            }
            set
            {
                this._arssList = value;
                RaisePropertyChanged("ArssList");
            }
        }

        public ObservableCollection<DoiTuongModel> DoiTuongList
        {
            get
            {
                return this._doituongList;
            }
            set
            {
                this._doituongList = value;
                RaisePropertyChanged("DoiTuongList");
            }
        }

        public ObservableCollection<ARSALESP> SaleSPList
        {
            get
            {
                return this._saleSPList;
            }
            set
            {
                this._saleSPList = value;
                RaisePropertyChanged("SaleSPList");
            }
        }

        public ARSALESP SelectedSaleSP
        {
            get
            {
                return this._selectedSaleSP;
            }
            set
            {
                this._selectedSaleSP = value;
                RaisePropertyChanged("SelectedSaleSP");
            }
        }

        public DoiTuongModel SelectedDoiTuong
        {
            get
            {
                return this._selectedDoiTuong;
            }
            set
            {
                this._selectedDoiTuong = value;
                if (this._selectedDoiTuong.Code == "SS")
                {
                    this.IsSS = true;
                    this.IsSaleSP = false;
                }
                else
                {
                    this.IsSS = false;
                    this.IsSaleSP = true;
                }
                RaisePropertyChanged("SelectedDoiTuong");
            }
        }

        public ARSS SelectedSS
        {
            get
            {
                return this._selectedSS;
            }
            set
            {
                this._selectedSS = value;
                RaisePropertyChanged("SelectedSS");
            }
        }

        public Distributor SelectedDistributor
        {
            get
            {
                return this._selectedDistributor;
            }
            set
            {
                this._selectedDistributor = value;
                if (this._selectedDistributor != null && this.SaleSPList != null)
                {
                    this.SaleSPList = new ObservableCollection<ARSALESP>(this._smartMobileContext.ARSALESP.Where(s => s.Sitecode == this._selectedDistributor.SiteCode));
                }

                RaisePropertyChanged("SelectedDistributor");
            }
        }

        #endregion

        #region Command

        public ICommandRoute ExitCommand
        {
            get;

            private set;
        }

        public ICommandRoute SaveCommand
        {
            get;

            private set;
        }

        public ICommandRoute UpdateCommand
        {
            get;

            private set;
        }

        #endregion

        #region ViewModelBase Overriden

        public override void Initialize(Uri uri)
        {

        }

        public override void PageLoaded(Uri uri)
        {
            this.IsBusy = true;
            if (GlobalInformation.NewDevice)
            {
                // Lay danh sach doi tuong
                this.GetDoituongList();
                this.SelectedDoiTuong = this.DoiTuongList[0];

                // Lay danh sach nhan vien
                this.GetARSaleSPList();

                // Lay danh sach cong ty
                this.GetDistributorList();


                if (this.SelectedDoiTuong.Code == "SS")
                {
                    // Lay danh sach giam sat
                    this.GetArssList();

                    if (ArssList != null && ArssList.Any())
                    {
                        this.SelectedSS = this.ArssList[0];
                    }
                }
                else
                {
                    if (SaleSPList != null && SaleSPList.Any())
                    {
                        this.SelectedSaleSP = this.SaleSPList[0];
                    }
                }
            }
            else
            {
                // Lay danh sach doi tuong
                this.GetDoituongList();

                // Lay danh sach cong ty
                this.GetDistributorList();

                // Lay danh sach nhan vien
                this.GetARSaleSPList();

                // Lay danh sach giam sat
                this.GetArssList();

                // Lay thong tin user tu local
                ARSALESPTYPE saleType = this._smartMobileContext.ARSALESPTYPE.FirstOrDefault();
                saleType.Workday = DateTime.Now.ToShortDateString();
                GlobalInformation.ArSaleSPType = saleType;
                this.IDDevice = saleType.IMEIID;
                this.PhoneNumber = saleType.Phonenumber;
                this.Webservice = saleType.Webserver;

                if (string.IsNullOrEmpty(saleType.Usertype))
                {
                    this.SelectedDoiTuong = this.DoiTuongList[0];
                }
                else
                {
                    this.SelectedDoiTuong = this.DoiTuongList.FirstOrDefault(d => d.Code == saleType.Usertype);
                }

                if (saleType.Usertype == "SS")
                {
                    // An list nhan vien va cong ty

                    if (string.IsNullOrEmpty(saleType.Usercode))
                    {
                        this.SelectedSS = this.ArssList[0];
                    }
                    else
                    {
                        this.SelectedSS = this.ArssList.FirstOrDefault(s => s.SSCode == saleType.Usercode);
                    }
                }
                else
                {
                    // An list giam sat
                    if (this.SaleSPList.Any())
                    {
                        if (string.IsNullOrEmpty(saleType.Usercode))
                        {
                            this.SelectedSaleSP = this.SaleSPList[0];
                        }
                        else
                        {
                            this.SelectedSaleSP = this.SaleSPList.FirstOrDefault(s => s.Salesp_key == saleType.Usercode);
                        }
                    }

                    if (DistributorList.Any())
                    {
                        if (string.IsNullOrEmpty(saleType.Sitecode))
                        {
                            this.SelectedDistributor = this.DistributorList[0];
                        }
                        else
                        {
                            this.SelectedDistributor = this.DistributorList.FirstOrDefault(s => s.SiteCode == saleType.Sitecode);
                        }
                    }
                }
            }

            this.IsBusy = false;
        }

        #endregion

        #region Command Action Handlers

        private void ExecuteExitCommand(object commandParams)
        {
            this.ExitCommand.RaiseCanExecuteChanged(true);
            base.PageNavigation.Navigate("Main");
        }

        private void ExecuteUpdateCommand(object commandParams)
        {
            if (string.IsNullOrEmpty(Webservice))
            {
                this.ShowMessage("Chưa nhập đường dẫn webservice");
                return;
            }

            base.IsBusy = true;
            byte[] uniqueIDbytes = (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId");
            string uniqueID = System.Convert.ToBase64String(uniqueIDbytes);

            StartWebRequest(@"http://" + Webservice + @"/ReloadDataSmartPhone.asmx");
            ////EndpointAddress _endpoint = new EndpointAddress(@"http://" + Webservice + @"/ReloadDataSmartPhone.asmx");
            ////_proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, _endpoint);
            ////_proxy.OpenCompleted += _proxy_OpenCompleted;
            ////_proxy.OpenAsync();

            this.UpdateCommand.RaiseCanExecuteChanged(true);
        }


        private void ExecuteSaveCommand(object commandParams)
        {
            if (this.SelectedDoiTuong.Code == "SS")
            {
                if (this.SelectedSS == null)
                {
                    this.ShowMessage("Lấy thông tin trước");
                    this.SaveCommand.RaiseCanExecuteChanged(true);
                    return;
                }
            }
            else
            {
                if (this.SaleSPList == null || (this.SaleSPList != null && !this.SaleSPList.Any()))
                {
                    this.ShowMessage("Lấy thông tin trước");
                    this.SaveCommand.RaiseCanExecuteChanged(true);
                    return;
                }
            }

            this.IsBusy = true;

            GlobalInformation.ConnectionStringWebService = Webservice;

            _proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);
            _proxy.GetSettingCompleted += Proxy_GetSettingCompleted;

            if (this.SelectedDoiTuong.Code == "SS")
            {
                _proxy.GetSettingAsync(GlobalInformation.SiteCode, SelectedDoiTuong.Code, this.SelectedSS.SSCode, this.IDDevice);                
            }
            else
            {
                 _proxy.GetSettingAsync(GlobalInformation.SiteCode, SelectedDoiTuong.Code, SelectedSaleSP.Salesp_key, this.IDDevice);
            }

            this.SaveCommand.RaiseCanExecuteChanged(true);
        }

        #endregion

        #region Web-service Event Handlers

        private void Proxy_GetArSaleSPCompleted(object sender, GetArSaleSPCompletedEventArgs e)
        {
            try
            {
                // Delete data before insert 
                if (_smartMobileContext.ARSALESP != null)
                {
                    _smartMobileContext.ARSALESP.DeleteAllOnSubmit(_smartMobileContext.ARSALESP.ToList());
                    _smartMobileContext.SubmitChanges();
                }

                // Add new data               
                // serializes the XML data to Object
                List<XmlARSaleSP> saleList = XmlHelper.GetItems<XmlARSaleSP>(e.Result.Nodes[1], "Table").ToList();

                ARSALESP sale = null;

                // converts to savable object-list
                foreach (XmlARSaleSP item in saleList)
                {
                    sale = new ARSALESP
                    {
                        ID_PK = Guid.NewGuid(),
                        Salesp_key = item.Salesp_Key,
                        Salesp_name = item.Salesp_name,
                        Sitecode = item.SiteCode,
                        SScode = item.SSCode
                    };

                    _smartMobileContext.ARSALESP.InsertOnSubmit(sale);
                }

                _smartMobileContext.SubmitChanges();

                this.GetARSaleSPList();

                _proxy.GetDistributorAsync(GlobalInformation.SiteCode);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void _proxy_OpenCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                if (_proxy.State == System.ServiceModel.CommunicationState.Opened)
                {
                    GlobalInformation.ConnectionStringWebService = Webservice;

                }
                else
                {
                    this.ShowMessage("Kiểm tra đường dẫn webservice");
                }
            }
            catch (Exception)
            {
            }
        }

        private void Proxy_GetSettingCompleted(object sender, GetSettingCompletedEventArgs e)
        {
            // serializes the XML data to Object
            List<XmlSetting> settingList = XmlHelper.GetItems<XmlSetting>(e.Result.Nodes[1], "Table").ToList();

            List<SqlSetting> settings = new List<SqlSetting>();
            SqlSetting localSetting = null;

            // converts to savable object-list
            foreach (XmlSetting setting in settingList)
            {
                localSetting = new SqlSetting
                {
                    AddinAfterPromotion = setting.AddinAfterPromotion,
                    AppStatus = setting.AppStatus,
                    Checkinloc = setting.Checkinloc,
                    ClosedWork = setting.ClosedWork,
                    ManagerSerial = setting.ManagerSerial,
                    NextArinvoice = setting.NextArinvoice,
                    OrderwhenVisit = setting.OrderwhenVisit,
                    PaycashAfterPromotion = setting.PaycashAfterPromotion,
                    PriceType = setting.PriceType,
                    ShowPrice = setting.ShowPrice,
                    Sitename = setting.Sitename
                };

                settings.Add(localSetting);
            }

            if (settings != null)
            {
                string checkStatus = settings.Select(s => s.AppStatus).FirstOrDefault();
                if (checkStatus == "1")
                {
                    // Get menu, thong tin 
                    // Delete old data
                    List<ARSALESPTYPE> currentSale = this._smartMobileContext.ARSALESPTYPE.ToList();
                    this._smartMobileContext.ARSALESPTYPE.DeleteAllOnSubmit(currentSale);
                    this._smartMobileContext.SubmitChanges();

                    ARSALESPTYPE saleSpType;

                    if (this.SelectedDoiTuong.Code == "SS")
                    {
                        saleSpType = new ARSALESPTYPE
                        {
                            ID_PK = Guid.NewGuid(),
                            IMEIID = this.IDDevice,
                            Webserver = this.Webservice,
                            Phonenumber = this.PhoneNumber,
                            Usertype = this.SelectedDoiTuong.Code,
                            Username = this.SelectedSS.SSName,
                            Usercode = this.SelectedSS == null ? string.Empty : this.SelectedSS.SSCode,
                            Sitename = string.Empty,
                            Sitecode = string.Empty
                        };

                        this._smartMobileContext.ARSALESPTYPE.InsertOnSubmit(saleSpType);
                        this._smartMobileContext.SubmitChanges();
                    }
                    else
                    {
                        saleSpType = new ARSALESPTYPE
                        {
                            ID_PK = Guid.NewGuid(),
                            IMEIID = this.IDDevice,
                            Webserver = this.Webservice,
                            Phonenumber = this.PhoneNumber,
                            Usertype = this.SelectedDoiTuong.Code,
                            Username = this.SelectedSaleSP.Salesp_name,
                            Usercode = this.SelectedSaleSP.Salesp_key,
                            Sitecode = this.SelectedDistributor.SiteCode,
                        };

                        this._smartMobileContext.ARSALESPTYPE.InsertOnSubmit(saleSpType);
                        this._smartMobileContext.SubmitChanges();
                    }

                    GlobalInformation.ArSaleSPType = saleSpType;
                    GlobalInformation.NewDevice = false;

                    this.ShowMessage("Lưu thành công");
                }
                else
                {
                    this.ShowMessage("Hãy nhập đủ thông tin trước khi lưu");
                }
            }

            this.IsBusy = false;
            this.SaveCommand.RaiseCanExecuteChanged(true);
        }

        private void Proxy_GetDistributorCompleted(object sender, GetDistributorCompletedEventArgs e)
        {
            try
            {
                // Delete data before insert 
                _smartMobileContext.Distributor.DeleteAllOnSubmit(_smartMobileContext.Distributor.ToList());
                _smartMobileContext.SubmitChanges();

                // Add new data              
                List<XmlDistributor> distributorList = XmlHelper.GetItems<XmlDistributor>(e.Result.Nodes[1], "Table").ToList();

                Distributor localDistributor = null;

                // converts to savable object-list
                foreach (XmlDistributor distributor in distributorList)
                {
                    localDistributor = new Distributor
                    {
                        ID_PK = Guid.NewGuid(),
                        SiteCode = distributor.SiteCode,
                        SiteName = distributor.Name,
                        Address = distributor.Address
                    };

                    _smartMobileContext.Distributor.InsertOnSubmit(localDistributor);
                }
                _smartMobileContext.SubmitChanges();

                this.GetDistributorList();
                base.IsBusy = false;
                this.ShowMessage("Lấy thông tin thành công");
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void Proxy_GetSSCompleted(object sender, GetSSCompletedEventArgs e)
        {
            try
            {
                //Delete data before insert 
                _smartMobileContext.ARSS.DeleteAllOnSubmit(_smartMobileContext.ARSS.ToList());
                _smartMobileContext.SubmitChanges();

                // Add new data
                // serializes the XML data to Object
                List<XmlARSS> xmlSSList = XmlHelper.GetItems<XmlARSS>(e.Result.Nodes[1], "Table").ToList();

                ARSS ss = null;

                // converts to savable object-list
                foreach (XmlARSS item in xmlSSList)
                {
                    ss = new ARSS
                    {
                        ID_PK = Guid.NewGuid(),
                        SSCode = item.SScode,
                        SSName = item.SSName
                    };

                    _smartMobileContext.ARSS.InsertOnSubmit(ss);
                }

                _smartMobileContext.SubmitChanges();
                
                this.GetArssList();
                _proxy.GetArSaleSPAsync(GlobalInformation.SiteCode);
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion

        #region Method

        private void StartWebRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.BeginGetResponse(result =>
            {
                App.RootFrame.Dispatcher.BeginInvoke(() =>
                {
                    FinishWebRequest(result, request);
                });
            }, null);
        }

        private void FinishWebRequest(IAsyncResult result, HttpWebRequest request)
        {
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        GlobalInformation.ConnectionStringWebService = Webservice;
                        _proxy = new ReloadDataSmartPhoneSoapClient(GlobalInformation.Binding, GlobalInformation.Endpoint);

                        if (this.SelectedDoiTuong.Code == "SS")
                        {
                            this._proxy.GetSSAsync(GlobalInformation.SiteCode);
                            this._proxy.GetSSCompleted += this.Proxy_GetSSCompleted;
                            _proxy.GetDistributorCompleted += this.Proxy_GetDistributorCompleted;
                            _proxy.GetArSaleSPCompleted += this.Proxy_GetArSaleSPCompleted;
                        }
                        else
                        {
                            _proxy.GetArSaleSPCompleted += this.Proxy_GetArSaleSPCompleted;
                            _proxy.GetDistributorCompleted += this.Proxy_GetDistributorCompleted;
                            _proxy.GetArSaleSPAsync(GlobalInformation.SiteCode);
                        }
                    }
                    else
                    {
                        //  well, at least it returned...
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowMessage("Kiểm tra đường dẫn webservice và kết nối Internet");
                base.IsBusy = false;
            }

        }

        private void GetDoituongList()
        {
            // Add default doituong Nhan vien, Giam sat, Ban hang

            DoiTuongModel nhanvien = new DoiTuongModel()
            {
                Name = "Field Force",
                Code = "DSR"
            };

            DoiTuongModel giamsat = new DoiTuongModel()
            {
                Name = "FF Teamleader",
                Code = "SS"
            };

            //DoiTuongModel giaonhan = new DoiTuongModel()
            //{
            //    Name = "Nhân viên giao nhận",
            //    Code = "RSU"
            //};

            this._doituongList = new ObservableCollection<DoiTuongModel>();

            this._doituongList.Add(nhanvien);
            this._doituongList.Add(giamsat);
            //this._doituongList.Add(giaonhan);

            this.DoiTuongList = this._doituongList;
        }

        private void GetARSaleSPList()
        {
            List<ARSALESP> sale = this._smartMobileContext.ARSALESP.ToList();
            this.SaleSPList = new ObservableCollection<ARSALESP>(sale);
            //if (this.SaleSPList.Any())
            //{
            //    this.SelectedSaleSP = this.SaleSPList[0];
            //}
        }

        private void GetDistributorList()
        {
            this.DistributorList = new ObservableCollection<SmartMobile.Data.Distributor>(this._smartMobileContext.Distributor);
            if (DistributorList != null && DistributorList.Any())
            {
                this.SelectedDistributor = this.DistributorList[0];
            }
        }

        private void GetArssList()
        {
            this.ArssList = new ObservableCollection<SmartMobile.Data.ARSS>(this._smartMobileContext.ARSS);
        }

        private void CreateConnection()
        {
            this._smartMobileContext = new SmartMobileDBContext(SmartMobileDBContext.ConnectionString);
            this._smartMobileContext.CreateIfNotExists();
            this._smartMobileContext.LogDebug = true;
        }
        #endregion
    }
}
